package com.itheima.users.dao;

import com.itheima.users.entity.User;

import java.io.*;
import java.util.*;

public class UserDatabaseInFile implements UserDatabase {
    private File file;

    public UserDatabaseInFile(String filePath) {
        this.file = new File(filePath);
        // 如果文件不存在，则创建
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.err.println("创建文件失败：" + e.getMessage());
            }
        }
    }

    // 从文件中读取用户数据
    private List<User> loadUsers() {
        if (file.length() == 0) {
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return (List<User>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("读取文件失败：" + e.getMessage());
            return new ArrayList<>();
        }
    }

    // 将用户数据写入文件
    private boolean saveUsers(List<User> users) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(users);
            return true;
        } catch (IOException e) {
            System.err.println("写入文件失败：" + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean save(User user) {
        List<User> users = loadUsers();

        // 检查用户名是否已存在
        for (User u : users) {
            if (u.getUsername().equals(user.getUsername())) {
                System.out.println("用户名已存在！");
                return false;
            }
        }

        users.add(user);
        return saveUsers(users);
    }

    @Override
    public User queryByUserId(String username) {
        if (username == null || username.isEmpty()) {
            return null;
        }

        List<User> users = loadUsers();

        for (User user : users) {
            if (user != null && username.equals(user.getUsername())) {
                return user;
            }
        }

        return null;
    }
}
